package com.hhhn.wk.main.fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.hhhn.wk.R;
import com.hhhn.wk.base.BaseFragment;
import com.hhhn.wk.entity.User;
import com.hhhn.wk.main.tab3.ShoppingCartAdapter;
import com.hhhn.wk.main.tab3.activity.ConfirmOrderCartActivity;
import com.hhhn.wk.main.tab3.entity.ShoppingCartBean;
import com.hhhn.wk.utils.AllPublic;
import com.hhhn.wk.utils.Constants;
import com.hhhn.wk.utils.SharePreferencesUser;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
/**
 * * * * * * * * * * * *
 * @author：文珂    ｡◕‿◕｡ *
 * Data：2018/3/15 0015    ｡◕‿◕｡ *
 * Function：      ｡◕‿◕｡ *
 * 购物车
 * * * * * * * * * * * */
public class TabFragment03 extends BaseFragment implements View.OnClickListener
        , ShoppingCartAdapter.CheckInterface, ShoppingCartAdapter.ModifyCountInterface {
    private static final String TAG = "ShoppingCartActivity";
    static DecimalFormat df   = new DecimalFormat("######0.00");
    MBroadcastReceiver mBroadcastReceiver;//广播接受者
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    initsetData();
                    break;
                case 2:
                    getSpecial();
                    break;
                case 3:
                    initData();
                    break;
            }
        }
    };
//    ArrayList<String> cartIdList=new ArrayList<>();
    //    Button btnBack;
    //全选
    CheckBox ckAll;
    //总额
    TextView tvShowPrice;
    //结算
    TextView tvSettlement;
    //编辑
    TextView btnEdit;//tv_edit

    ListView list_shopping_cart;
    private ShoppingCartAdapter shoppingCartAdapter;
    private boolean flag = false;
    private List<ShoppingCartBean> shoppingCartBeanList = new ArrayList<>();
    private boolean mSelect;
    private double totalPrice = 0.00;// 购买的商品总价
    private int totalCount = 0;// 购买的商品总数量

    LinearLayout ll_n;
    LinearLayout ll_p;
    LinearLayout ll_0;
    public TabFragment03() {
        // Required empty public constructor
    }
    @Override
    protected void initView(View mRootView) {

//      btnBack= (Button) findViewById(R.id.btn_back);
        ckAll= (CheckBox) findViewById(R.id.ck_all);
        tvShowPrice= (TextView) findViewById(R.id.tv_show_price);
        tvSettlement= (TextView) findViewById(R.id.tv_settlement);
        btnEdit= (TextView) findViewById(R.id.bt_header_right);
        list_shopping_cart= (ListView) findViewById(R.id.list_shopping_cart);

        ll_n=  findViewById(R.id.ll_n);
        ll_p=  findViewById(R.id.ll_p);
        ll_0=  findViewById(R.id.ll_0);

        btnEdit.setOnClickListener(this);
        ckAll.setOnClickListener(this);
        tvSettlement.setOnClickListener(this);
//      btnBack.setOnClickListener(this);
        mBroadcastReceiver = new MBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        //设置接收广播的类型
        intentFilter.addAction(Constants.MBroadcastReceiverCart);
        //调用Context的registerReceiver（）方法进行动态注册
        mActivity.registerReceiver(mBroadcastReceiver, intentFilter);
    }
    private void initsetData(){
        shoppingCartAdapter = new ShoppingCartAdapter(mActivity);
        shoppingCartAdapter.setCheckInterface(this);
        shoppingCartAdapter.setModifyCountInterface(this);
        list_shopping_cart.setAdapter(shoppingCartAdapter);
        shoppingCartAdapter.setShoppingCartBeanList(shoppingCartBeanList);


        if (shoppingCartBeanList.size()==0){
            ll_n.setVisibility(View.GONE);
            ll_0.setVisibility(View.VISIBLE);
            ll_p.setVisibility(View.GONE);
        }else {
            ll_n.setVisibility(View.GONE);
            ll_0.setVisibility(View.GONE);
            ll_p.setVisibility(View.VISIBLE);
        }

        for (int i = 0; i < shoppingCartBeanList.size(); i++) {
            shoppingCartBeanList.get(i).setChoosed(false);
        }
        shoppingCartAdapter.notifyDataSetChanged();
        statistics();
    }
    @Override
    protected void initData() {
        User user = (User) SharePreferencesUser.getBean(mActivity,Constants.USER);
        Log.d("user", user+"");
        if (user==null){
            ll_n.setVisibility(View.VISIBLE);
            ll_p.setVisibility(View.GONE);
            ll_0.setVisibility(View.GONE);
        }else {
            int isLogin = user.getIsLogin();
            if (isLogin == 0) {
                ll_n.setVisibility(View.VISIBLE);
                ll_p.setVisibility(View.GONE);
                ll_0.setVisibility(View.GONE);
            } else if (isLogin == 2) {//正常
                ll_n.setVisibility(View.GONE);
                ll_0.setVisibility(View.GONE);
                ll_p.setVisibility(View.VISIBLE);
                getSpecial();
            } else {

            }
        }
    }
    @Override
    protected void initClick() {
        ll_n.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AllPublic.isLogin(mActivity,mActivity);
            }
        });
    }
    @Override
    protected int setLayoutResouceId() {
        return R.layout.fragment_tab_fragment03;
    }
    /**
     * 结算订单、支付
     */
    private void lementOnder() {
        ArrayList<String> cartIdList=new ArrayList<>();
        //选中的需要提交的商品清单
        for (ShoppingCartBean bean:shoppingCartBeanList ){
            boolean choosed = bean.isChoosed();
            if (choosed){
                String shoppingName = bean.getShoppingName();
                int count = bean.getCount();
                double price = bean.getPrice();
                int size = bean.getDressSize();
                String attribute = bean.getAttribute();
                String id = bean.getId();
                cartIdList.add(id);
                Log.d(TAG,id+"----id---"+shoppingName+"---"+count+"---"+price+"--size----"+size+"--attr---"+attribute);
            }
        }
//        toastWk("总价："+totalPrice);
        //跳转到确认订单页面
        if (totalCount==0){
            toastWk("请选择商品");
            return;
        }
         Intent intent=new Intent(mActivity, ConfirmOrderCartActivity.class);
         intent.putExtra("tpye",1);//1购物车跳转   2商品直接跳转
         intent.putStringArrayListExtra("cartIdList",cartIdList);
         startActivity(intent);
    }
    /**
     * 单选
     * @param position  组元素位置
     * @param isChecked 组元素选中与否
     */
    @Override
    public void checkGroup(int position, boolean isChecked) {
        shoppingCartBeanList.get(position).setChoosed(isChecked);
        if (isAllCheck())
            ckAll.setChecked(true);
        else
            ckAll.setChecked(false);
        shoppingCartAdapter.notifyDataSetChanged();
        statistics();
    }
    /**
     * 遍历list集合
     * @return
     */
    private boolean isAllCheck() {
        for (ShoppingCartBean group : shoppingCartBeanList) {
            if (!group.isChoosed())
                return false;
        }
        return true;
    }
    /**
     * 统计操作
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作
     * 3.给底部的textView进行数据填充
     */
    public void statistics() {
        totalCount = 0;
        totalPrice = 0.00;
        for (int i = 0; i < shoppingCartBeanList.size(); i++) {
            ShoppingCartBean shoppingCartBean = shoppingCartBeanList.get(i);
            if (shoppingCartBean.isChoosed()) {
                totalCount++;
                totalPrice += shoppingCartBean.getPrice() * shoppingCartBean.getCount();
            }
        }
        tvShowPrice.setText("合计:" + df.format(totalPrice));
        tvSettlement.setText("结算(" + totalCount + ")");
    }
    /**
     * 增加
     * @param position      组元素位置
     * @param showCountView 用于展示变化后数量的View
     * @param isChecked     子元素选中与否
     */
    @Override
    public void doIncrease(int position, View showCountView, boolean isChecked) {
        getJia( position,showCountView,isChecked);

    }
    /**
     * 删减
     * @param position      组元素位置
     * @param showCountView 用于展示变化后数量的View
     * @param isChecked     子元素选中与否
     */
    @Override
    public void doDecrease(int position, View showCountView, boolean isChecked) {
        getJian( position,showCountView,isChecked);

    }
    /**
     * 删除
     * @param position
     */
    @Override
    public void childDelete(int position) {
        getDEL(position);
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //全选按钮
            case R.id.ck_all:
                if (shoppingCartBeanList.size() != 0) {
                    if (ckAll.isChecked()) {
                        for (int i = 0; i < shoppingCartBeanList.size(); i++) {
                            shoppingCartBeanList.get(i).setChoosed(true);
                        }
                        shoppingCartAdapter.notifyDataSetChanged();
                    } else {
                        for (int i = 0; i < shoppingCartBeanList.size(); i++) {
                            shoppingCartBeanList.get(i).setChoosed(false);
                        }
                        shoppingCartAdapter.notifyDataSetChanged();
                    }
                }
                statistics();
                break;
            case R.id.bt_header_right:
                flag = !flag;
                if (flag) {
                    btnEdit.setText("完成");
                    shoppingCartAdapter.isShow(false);
                } else {
                    btnEdit.setText("编辑");
                    shoppingCartAdapter.isShow(true);
                }
                break;
            case R.id.tv_settlement: //结算
                lementOnder();
                break;
        }
    }
    //获取购物车
    private void getSpecial(){
        mActivity. showLoad();
        RequestParams params = AllPublic.getParamsCart(mActivity, "/cartList", false);
        params.addParameter("merchantId",mActivity.getUser().getUid());
        Log.d("QQ获取购物车", "getJSON: "+params);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                Log.d("获取购物车：", result);
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {
                        JSONArray records = jsonObject.getJSONArray("data");
                        ShoppingCartBean shoppingCartBean=null;
                        for (int i=0;i<records.length();i++){
                            shoppingCartBean=new ShoppingCartBean();
                            JSONObject object = records.getJSONObject(i);
                            String id = object.has("id") ? object.getString("id") : "";
                            String keywords = object.has("name") ? object.getString("name") : "";//标题
                            double price = object.has("price") ? object.getDouble("price") : 0;//单价
                            String rotation_chart = object.has("product_picture") ? object.getString("product_picture") : "";//商品主图
                            int number = object.has("number") ? object.getInt("number") : 0;//商品数量
                            shoppingCartBean.setShoppingName(keywords);
                            shoppingCartBean.setPrice(price);
                            shoppingCartBean.setId(id);
                            shoppingCartBean.setCount(number);
                            shoppingCartBean.setImageUrl(rotation_chart);
                            shoppingCartBeanList.add(shoppingCartBean);
                        }
                        handler.sendEmptyMessage(1);
                    }else {
                        mActivity.toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mActivity. dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                mActivity.  dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {
                mActivity.  dismissLoad();
            }
            @Override
            public void onFinished() {
                mActivity.  dismissLoad();
            }
        });
    }
    //删除一条购物车
    private void getDEL(final int position){
        mActivity. showLoad();
        RequestParams params = AllPublic.getParamsCart(mActivity, "/delCart", false);
        params.addParameter("id",shoppingCartBeanList.get(position).getId());
        Log.d("删除一条购物车", "getJSON: "+params);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                Log.d("删除一条购物车：", result);
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {
                        shoppingCartBeanList.remove(position);
                        shoppingCartAdapter.notifyDataSetChanged();
                        statistics();
                    }else {
                        mActivity.toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }
                mActivity. dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                ex.printStackTrace();
                mActivity.  dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {

                mActivity.  dismissLoad();
            }
            @Override
            public void onFinished() {

                mActivity.  dismissLoad();
            }
        });
    }
    //一条购物车--增加
    private void getJia(final int position,final View showCountView,final boolean isChecked){
        mActivity. showLoad();
        RequestParams params = AllPublic.getParamsCart(mActivity, "/addOrSub", false);
        params.addParameter("type",0);//0 加 1 减
        params.addParameter("id",shoppingCartBeanList.get(position).getId());
        Log.d("一条购物车--增加", "getJSON: "+params);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                Log.d("一条购物车--增加：", result);
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");

                    if (reason.equals("0")) {
                        JSONObject data = jsonObject.getJSONObject("data");
                        double price = data.getDouble("price");
                        ShoppingCartBean shoppingCartBean = shoppingCartBeanList.get(position);
                        int currentCount = shoppingCartBean.getCount();
                        currentCount++;
                        shoppingCartBean.setPrice(price);
                        shoppingCartBean.setCount(currentCount);
                        ((TextView) showCountView).setText(currentCount + "");
                        shoppingCartAdapter.notifyDataSetChanged();
                        statistics();
                    }else {
                        mActivity.toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mActivity. dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                ex.printStackTrace();
                mActivity.  dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {

                mActivity.  dismissLoad();
            }
            @Override
            public void onFinished() {

                mActivity.  dismissLoad();
            }
        });
    }
    //一条购物车--减去
    private void getJian(final int position,final View showCountView,final boolean isChecked){
        mActivity. showLoad();
        RequestParams params = AllPublic.getParamsCart(mActivity, "/addOrSub", false);
        params.addParameter("type",1);//0 加 1 减
        params.addParameter("id",shoppingCartBeanList.get(position).getId());
        Log.d("一条购物车--增加", "getJSON: "+params);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                Log.d("一条购物车--增加：", result);
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {
                        JSONObject data = jsonObject.getJSONObject("data");
                        double price = data.getDouble("price");



                        ShoppingCartBean shoppingCartBean = shoppingCartBeanList.get(position);
                        int currentCount = shoppingCartBean.getCount();
                        if (currentCount == 1) {
                            return;
                        }
                        currentCount--;
                        shoppingCartBean.setPrice(price);
                        shoppingCartBean.setCount(currentCount);
                        ((TextView) showCountView).setText(currentCount + "");
                        shoppingCartAdapter.notifyDataSetChanged();
                        statistics();
                    }else {
                        mActivity.toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                        mActivity.toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }
                mActivity. dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                ex.printStackTrace();
                mActivity.  dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {

                mActivity.  dismissLoad();
            }
            @Override
            public void onFinished() {

                mActivity.  dismissLoad();
            }
        });
    }
    public class MBroadcastReceiver extends BroadcastReceiver {
        //接收到广播后自动调用该方法
        @Override
        public void onReceive(Context context, Intent intent) {
            //写入接收广播后的操作
            Log.d(TAG, "购物车: 接收广播");
            if (shoppingCartBeanList!=null){
                shoppingCartBeanList.clear();
            }
            if (shoppingCartAdapter!=null){
                shoppingCartAdapter.notifyDataSetChanged();
            }
          handler.sendEmptyMessage(3);
//            ll_n.setVisibility(View.VISIBLE);
//            ll_p.setVisibility(View.GONE);
//            ll_0.setVisibility(View.GONE);
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        mActivity.unregisterReceiver(mBroadcastReceiver);
    }
}
